/**
 * auth ctfo wanghua 2013-3-1
 * 参数说明：
 * setting = {
 * 		limit: 10,          //每页数据行数
 * 		dataSource: 'url',  //数据获取url，请求数据是会自动在url上加上start和limit参数,start为起始行数,从0开始
 * 		colModel :          //列信息，与table的td元素按顺序对应 
 * 		  [
 * 			{name:'colName',renderer : function(v, rowData , rowIndex){return ...}},
 * 			{}
 * 		  ],
 * 		pageType: 'local',  //分页方式：'local', 'server'。 本地分页：第一次从服务器获取全部数据之后，在本地进行分页，服务器分页：每次分页数据都从服务器获取
 * 		pagePanel: 'pagePanelId',//分页条元素的id
 * 		fillRows : false         //数据行数不足 limit时，是否填充空行
 * }
 *  api:
 *  var _tab1; //注意，此处定义为全局变量，不能定义为局部变量
 *  ......
 *  if(_tab1 == null){
    	_tab1 = $("#tab1").dkGrid(setting); //初始化,同一个table不能初始化两次
    }else{
    	_tab1.reload(setting); //再次加载数据
    }
    
 * 使用方法：dkGrid
 * 引用文件：
 *  <link href="../../css/dkgrid.css" rel="stylesheet" type="text/css" />
	<link href="../../css/style.css" rel="stylesheet" type="text/css" />
	<link href="../../css/pagination.css" rel="stylesheet" type="text/css" />
	<script src="../../js/jquery-1.8.3.min.js" type="text/javascript" ></script>
	<script src="../../js/form/dkGrid.js" type="text/javascript" ></script>

var _tab;

if(!_tab){
	_tab = $("#tab").dkGrid(dkGridSetting);
	
} else{
	_tab.reload(dkGridSetting);
}
    
 * 1. 制作一个样式美观的table原型
 *   1.1 在页面中添加一个 table 元素，
 *   1.2 使用 thead 元素制作好表头
 *   1.3 使用tbody,tr,td元素制作一行数据
 *   1.4 分页条可以引用 <%@ include file="../common/pager.html"%>
 * 2.使用dkGrid组件来填充数据
 *    $(document).ready(function() {
		 
		_tab1 = $("#tab1").dkGrid({
			colModels:[  
				{name:'_seqnum_'},
				{name:'_seqnum_'},
				{name:'name'},
				{name:'required',renderer : function(v, rowData , rowIndex){return v==true?'是':'否';}},
				{name:'appearTimes',},
				{name:'define',},
				{name:'id',renderer:function(value){
		                			 var exp='<a href="addDataElementDef.jsp?id='+value+'">删除</a>'; 
							         return exp;}}
			],
			limit : 4,
			fillRows : true,
			dataSource : 'http://localhost:8001/DataCenter/rest/base/dataElementDefHandler/getDataElementsByPage?js_plugin_type=OMGridPage',			
			urlParam : {},
			pagePanel: 'pagePanel',
			pageType : 'server',
			callback:{
				beforePageRender : null,//beforeGotoPage(pageIndex,pageSize,totalPages)
				afterPageRender : null,
				beforeRenderRow : null,
				beforeGotoPage : null,
				afterGotoPage : null				
			}
		});  
 * 
 * 
 * 保持页面刷新时自动定位到上一次的页号：
 *  1、在dkGrid所在JSP页面中引入comm.jsp，如<%@ include file="/jsp/metadata/framework/comm.jsp"%>  
 *  2、在刷新dkGrid所在的JSP页面时，URL参数带上：keepPage=true,
 *     如onclick="window.location='<%=basePath%>jsp/metadata/DataElementDef/dataElementDef.jsp?dataType=0&keepPage=true'
 */

(function($) {
	$.fn.dkGrid=function(setting){
		var grid = $(this);
		var plugin = {
			s:'xyzabc',
			self : this,
			setting : setting,
			callback : {},
			pageData : {},
			grid : grid,
			pagePanel : '',
			pageType : setting.pageType,
			colModels : setting.colModels,		
			tbody : '',
			tr_tmp : [],			
			HtmlSpecialChars : function(str){
				if(typeof(str) != 'string')return str;			
		        var s = "";
		        if (str.length == 0) return "";
		        for(var i=0; i<str.length; i++)
		        {
		            switch (str.substr(i,1))
		            {
		                case "<": s += "&lt;"; break;
		                case ">": s += "&gt;"; break;
		                case "&": s += "&amp;"; break;
		                case " ":
		                    if(str.substr(i + 1, 1) == " "){
		                        s += " &nbsp;";
		                        i++;
		                    } else s += " ";
		                    break;
		                case "\"": s += "&quot;"; break;
		                case "\n": s += "<br>"; break;
		                default: s += str.substr(i,1); break;
		            }
		        }
		        return s;
			},
			
			apply:function(fun,param, defaultValue){
				
				if ((typeof fun) == "function") {
					return fun.apply(this, param?param:[]);
				}
				return defaultValue;
			},
			
			_buildRowCellValue : function(colModel,rowData,rowIndex){
				var self = this;
	            var c=colModel,
	            	v,
	            	r=c.renderer;
	            if(!c.name) return "";
	            if(c.name.indexOf(".") > 0){
	            	var properties = c.name.split("."),
	            		j = 1,
	            		length = properties.length,
	            		v = rowData[properties[0]];
	            	while(j<length && v && (v=v[properties[j++]]) != undefined){}
	            }            
	            if(v == undefined){
	            	v = rowData[c.name] == undefined? "" : rowData[c.name];
	            	v = self.HtmlSpecialChars(v);
	            }
	            if(typeof r === 'function'){
	            	v = self.HtmlSpecialChars(v);
	                v = r(v,rowData,rowIndex,colModel);
	            }
	            return v;
        	},
        	
        	gotoPage : function(evt){
        		var self = this;
	        	var op = self.setting;
	        	var pageParam = evt.data;
	        	//alert(JSON.stringify(pageParam));
	        	var pageIndex = pageParam.pageIndex;
	        	var pageSize = op.limit>0?op.limit:100000;
	        	var totalPages = self.pageData.totalPages;
	        	if(pageIndex <1) pageIndex = 1;
	        	if(pageIndex > totalPages) pageIndex = totalPages;
	        	
	        	var nowPage = self.pageData.nowPage;
	        	if(pageIndex == nowPage) return;
	        	self.apply(self.callback.beforeGotoPage,[pageIndex,pageSize,totalPages],true);
	        	if(op.pageType == 'local'){
	        		self.createGridPageClient(pageIndex,pageSize,true);	        		
	        	}else {
	        		self.createGridPageServer(pageIndex,pageSize);
	        	}
	        	
        	},
        	
        	/**从服务器获取分页数据
	         * pageIndex第几页，从1开始   pageSize 每页记录数**/
	        createGridPageServer : function (pageIndex,pageSize){
	        	var self = this;
	        	//alert(pageIndex);
	        	var op = self.setting; 
	        	//alert(pageIndex);
	        	self.pageData.nowPage = pageIndex;
	        	self._populate();
	        },
	        
	        createGridPageClient : function (pageIndex,pageSize){
	        	var self = this;
	        	self.pageData.nowPage = pageIndex;
	        	self._buildPager();
	        	self._rendererDatas();
        	},
	        padLeft : function (v,len){
	        	s = '' + v;
	        	while(s.length < len){
	        		s = ' ' + s;
	        	}
	        	while(s.indexOf(' ')>=0)s = s.replace(' ','&nbsp;');
	        	
	        	return s;
	        },
	        
	        _buildPager : function (){
	        	var self = this;
	        	if(!self.pagePanel)return;
	        	var op = self.setting;
	        	if(!self.pageData || !self.pageData.data || !self.pageData.data.rows) return;
	        	
				if(!self.pageData.data.total) self.pageData.data.total = self.pageData.data.rows.length;
				var totalRows = self.pageData.data.total;
				
				var pageSize = op.limit;
				if(!pageSize) pageSize = 100000000;
				var nowPage = self.pageData.nowPage;
				if(!nowPage) nowPage = 1;
				var totalPage = Math.ceil(totalRows/pageSize);
				var beginRow = (nowPage - 1) * pageSize + 1;
				var endRow = beginRow + pageSize-1;
				if(endRow > totalRows) endRow = totalRows;
				if(endRow == 0)beginRow = 0;
				//alert(pageSize + "," + totalRows);
							
				var c_pageSum = $("#pageSum",self.pagePanel);
				if(c_pageSum){
					var pageSumHtml = c_pageSum.attr("desc");	
					if(!pageSumHtml)pageSumHtml = "显示#totalRows#个记录中的#beginRow#到#endRow#";
					 
					pageSumHtml = pageSumHtml.replace('#totalRows#',self.padLeft(totalRows,4));
					pageSumHtml = pageSumHtml.replace('#beginRow#',self.padLeft(beginRow,4));
					pageSumHtml = pageSumHtml.replace('#endRow#',self.padLeft(endRow,4));			
					c_pageSum.html(pageSumHtml);
				}
				
				//alert($("#firstPage",pagePanel).html());
				var c_firstPage = $("#firstPage",self.pagePanel);
				if(c_firstPage){
					c_firstPage.unbind();
					c_firstPage.bind("mousedown",{pageIndex:1},function(event) {
									return self.gotoPage(event);
								});
				}
				
				var c_lastPage = $("#lastPage",self.pagePanel);
				if(c_lastPage){
					c_lastPage.unbind();
					c_lastPage.bind("mousedown",{pageIndex:totalPage},function(event) {
									return self.gotoPage(event);
								});
				}
				
				var c_prePage = $("#prePage",self.pagePanel);
				if(c_prePage){
					c_prePage.unbind();
					c_prePage.bind("mousedown",{pageIndex:nowPage-1},function(event) {
									return self.gotoPage(event);
								});
				}
				
				var c_nextPage = $("#nextPage",self.pagePanel);
				
				if(c_nextPage){
					c_nextPage.unbind();
					c_nextPage.bind("mousedown",{pageIndex:nowPage+1},function(event) {
									return self.gotoPage(event);
								});
				}
							 
				var c_pageIndex = $("#pageIndex",self.pagePanel);
				var pageNumHtml = "";
				if(c_pageIndex){ //显示页数导航。
					var pageGap = 4;
					var startPageIndex = nowPage - pageGap;
					var endPageIndex = nowPage + pageGap;
					if(startPageIndex<1) {
						endPageIndex = endPageIndex + (1-startPageIndex); //前面不足，后面补足
						startPageIndex = 1;//前面超出，掐掉
						
					}
					if(endPageIndex > totalPage) {
						startPageIndex = startPageIndex - (endPageIndex - totalPage); //后面不足，前面补足
						endPageIndex = totalPage;//后面超出，掐掉
					}
					
					if(startPageIndex<1) startPageIndex = 1;  //前面超出，掐掉
					if(endPageIndex > totalPage) endPageIndex = totalPage; //后面超出，掐掉
					for(i=startPageIndex;i<=endPageIndex;++i){
						cssName = 'pagenum';
						if(i == nowPage){
							cssName = 'current';
						}
						pageNumHtml = pageNumHtml + "<span id=page"+i+" class='"+cssName+"'>"+i+"</span>"; 
					}
					if(!pageNumHtml)pageNumHtml = "<span ></span>";
					c_pageIndex.html(pageNumHtml);
					
					for(i=startPageIndex;i<=endPageIndex;++i){
						var cid = '#page'+i;
						var c_xPageIndex = $(cid,c_pageIndex);
						if(c_xPageIndex){
							c_xPageIndex.unbind();
							//c_xPageIndex.bind("mousedown",{pageIndex:i},self.gotoPage);
							c_xPageIndex.bind("mousedown",{pageIndex:i},
								function(event) {
									return self.gotoPage(event);
								});
						}
					}
				}
	        },
	        
	        _rendererDatas : function (){
	        	var self = this;
				var op = setting;
				if(!self.pageData || !self.pageData.data || !self.pageData.data.rows) return;
				
				if(!self.pageData.data.total) self.pageData.total = self.pageData.data.rows.length;
				var rows = self.pageData.data.rows;
				
				 
				if(rows){
					var colModelLen = self.colModels.length;
					var rowsCount = rows.length;
					var pageIndex = self.pageData.nowPage; 
					var index=0;
					var lastCount = rowsCount;
					var seqnum = 1;
					this.setCookie('dkGridPage',self.pageData.nowPage);
					if(op.pageType=='local'){
						index = (self.pageData.nowPage - 1) * op.limit;
						if(index < 0) index = 0;
						
						lastCount = index + op.limit;
						if(lastCount > rowsCount) lastCount = rowsCount;
						seqnum = index;
					}else{
						seqnum = (self.pageData.nowPage - 1) * op.limit;
					}
					var listRowCount = 0;
					//alert(op.pageType+':'+index+','+lastCount+" op.limit:"+op.limit);
					var sidx = 0;
					self.tbody.html("");
					for(index;index<lastCount;++index){
						++seqnum;
						var item = rows[index];				
						
						sidx = sidx % self.tr_tmp.length;
						
		        		var tr = self.tr_tmp[sidx].clone(true);
		        		
						++sidx;
		        		var rowIndex = index;
		        		var rowData = item;
		        		self.apply(self.callback.beforeRenderRow,[rowData,rowIndex],false);
		        		$("td",tr).each(function(colIndex,td){		        			
		        			if(colIndex < colModelLen){
			        			var colModel = self.colModels[colIndex];
			        			var text = '';
			        			if(colModel.name =='_seqnum_'){
			        				text = seqnum;
			        			}else{
			        				text = self._buildRowCellValue(colModel,rowData,rowIndex);
			        			}
			        			$(this).html(text);
		        			}
		        		})
		        		 
		        		tr.appendTo(self.tbody); 
		        		++listRowCount;
		        	}
					
					if(op.fillRows && listRowCount < op.limit){					
						for(i=listRowCount;i<op.limit;++i){
							sidx = sidx % self.tr_tmp.length;
							var tr = self.tr_tmp[sidx].clone();
							++sidx;
							$("td",tr).each(function(colIndex,td){  
			        			if(colIndex < colModelLen){			        			
				        			$(this).html("&nbsp;");
			        			}
			        		})
			        		tr.appendTo(self.tbody); 
						}
					}
					if(self.setting.onFillData){
						self.setting.onFillData();
					} 
					self.apply(self.callback.afterGotoPage,[pageIndex,listRowCount],true);
				}				
			},
		
			_addData : function (data){
				var self = this;
				var op = setting;				 
	            self.pageData.data=data;
	            self.pageData.totalPages = Math.ceil(data.total/op.limit);

	            //刷新分页条
	            self._buildPager();
	            self._rendererDatas();
			},
			
			//刷新数据
			_populate : function () { // get latest data
				var self = this;
	            var op = self.setting;            
	            if (!op.dataSource) {               
	                return false;
	            }
	            if (self.loading) {
	                return true;
	            }
	           
	            var nowPage = self.pageData.nowPage || 1;
	          
	            self.pageData.nowPage = nowPage;

	            //具备加载数据的前提条件了，准备加载
	            self.loading = true;
	            
	            var limit = (!op.limit || op.limit<=0)?100000000:op.limit;
	            
	            
	            op.limit = limit;
	            
	            var param ={};
	            if(op.urlParam){
	            	param = op.urlParam;
	            }
	            param.start = limit * (nowPage - 1);
				param.limit = limit;
	            param._time_stamp_ = new Date().getTime();
	            if(op.pageType == 'local'){  //如果采用前台分页
	            	self.pageData.nowPage = nowPage;
	            	param.limit = 10000;
	            }

	            var outClass = this;
	            $.ajax({
	                type : op.method,
	                url : op.dataSource,
	                data : param,
	                dataType : 'json',
	                contentType: "application/x-www-form-urlencoded; charset=utf-8",
	                success : function(data,textStatus,request) {
	                    var onSuccess = outClass.setting.onSuccess;
	                    if (typeof(onSuccess) == 'function') {
	                    	onSuccess(data,textStatus,request);
	                    }

	                    outClass._addData(data);
	                    
	                    var onRefresh = outClass.setting.onRefresh;
	                    if (typeof(onSuccess) == 'function') {
	                    	onRefresh(nowPage,data.rows);
	                    }
	                    self.loading = false;
	                },
	                error : function(XMLHttpRequest, textStatus, errorThrown) {                   
	                    try {
	                        var onError = outClass.setting.onError;
	                        if (typeof(onError) == 'function') {
	                            onError(XMLHttpRequest, textStatus, errorThrown);
	                        }
	                    } catch (e) {
	                        // do nothing 
	                    } finally {
	                         
	                        self.loading = false;
	                        pageData.data={rows:[],total:0};//出错时重新设置，不然self.pageData.data可能为undefined，其它地方就要做多余空处理
	                        return false;
	                    }
	                }
	            });
	        },
			
			reload : function(setting){
				var self = this;        		
        		self._init(setting);
        	},
        
			_init : function(setting){
				//if(grid.attr('dkgrid_created') == 'true'){
				//	alert('表格已经初始化过一次，不能再次初始化，请使用reload方法重新加载数据');
				//}
				//grid.attr('dkgrid_created','true');
				   
				var self = this;				
				self.setting = setting; 
				 
				if("undefined" == typeof(self.setting.callback)){
					self.setting.callback = {};
				}
				self.callback = self.setting.callback;
				pageData={nowPage:1,totalPages:1};
				if(!self.setting.method) self.setting.method = 'GET';
					
				self.pagePanel = $('#'+self.setting.pagePanel);
				self.pageType = self.setting.pageType;
				if(self.pageType != 'server' && self.pageType != 'local'){
					self.setting.pageType = 'local';
				}
				//alert(typeof(pagePanel.html()));
				if(setting.colModels){
					self.colModels = setting.colModels;
				}
				
				self.tbody = $("tbody",grid);
				if(!self.tr_tmp || self.tr_tmp.length==0 || setting.reinit==true){
					var tr_tmp1 = $("tr",self.tbody).eq(0);
					 
					var tr_tmp2 = $("tr",self.tbody).eq(1);
					self.tr_tmp = [tr_tmp1.clone(true)]; 
					if(tr_tmp2.length>0) self.tr_tmp = [tr_tmp1.clone(true),tr_tmp2.clone(true)];
					 
				}else{
					//alert(tr_tmp.length);
				}
				
				//
				self.tbody.html("");
				
				var op = self.setting;
				//从 include的top.jsp中获取request中的keepPage值
				var keepPageIndex = 'false';
				if("undefined" != typeof(keepPage)){
					keepPageIndex = keepPage;
				}else if(parent){
					keepPageIndex = parent.keepPage;
				} 
				var thisUrlParamStr = '';
				if(op.urlParam) thisUrlParamStr = JSON.stringify(op.urlParam);
				if(keepPageIndex == 'true'){
					var lastPageIndex = 1;
					//从cookie中取出url
					var ckUrl = this.getCookie('dkGridUrl');
					var dkUrlParam = this.getCookie('dkGridUrlParam');
					if(!dkUrlParam) dkUrlParam = '';
					//如果url匹配，则取出页数
					if(ckUrl == op.dataSource && dkUrlParam == thisUrlParamStr){
						lastPageIndex = this.getCookie('dkGridPage');
						if(!lastPageIndex) lastPageIndex = 1;
						else lastPageIndex = parseInt(lastPageIndex);
						self.pageData.nowPage = lastPageIndex;//设置显示第几页	
					}
				}
				this.setCookie('dkGridUrl',op.dataSource);
				this.setCookie('dkGridUrlParam',thisUrlParamStr);
				 
				//alert(JSON.stringify(op));
				var dataSource = op.dataSource;
				if(dataSource){
					self._populate();
				}else{
					var data = setting.data;					
					if(data){						
						var nowPage = self.pageData.nowPage || 1;
	           			self.pageData.nowPage = nowPage;
						self._addData(data);
					}
				}
				
			},
			
			alertjson:function(obj){
				alert(JSON.stringify(obj));
			},
			
			setCookie:function(name,value)//两个参数，一个是cookie的名称，一个是值
			{
			    var Days = 30; //此 cookie 将被保存 30 天
			    var exp  = new Date();    //new Date("December 31, 9998");
			    exp.setTime(exp.getTime() + Days*24*60*60*1000);
			    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
			},
			getCookie:function(name)//取cookies函数        
			{
			    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
			     if(arr != null) return unescape(arr[2]); return null;

			},
			delCookie:function(name)//删除cookie
			{
			    var exp = new Date();
			    exp.setTime(exp.getTime() - 1);
			    var cval=getCookie(name);
			    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
			}
			
		};
     		
		plugin._init(setting); 
		return plugin;
	};		
})(jQuery);